<template>
  <div class="dep">
    <div>
      <el-input
        class="el-input_search depTreeSearch"
        placeholder="输入关键字进行部门过滤"
        prefix-icon="el-icon-search"
        v-model="filterDepText"
      >
      </el-input>

      <el-tree
        class="filter-tree"
        :data="department"
        :props="departmentProps"
        default-expand-all
        node-key="id"
        :expand-on-click-node="false"
        :filter-node-method="filterDepNode"
        ref="tree"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span class="custom-tree-button-span">
            <el-button
              type="primary"
              size="mini"
              @click="() => showAddDep(data)"
              class="custom-tree-button"
            >
              添加部门
            </el-button>
            <el-button
              type="danger"
              size="mini"
              @click="() => doDepDelete(data)"
              class="custom-tree-button"
            >
              删除部门
            </el-button>
          </span>
        </span>
      </el-tree>
    </div>
    <div>
      <el-dialog title="添加部门" :visible.sync="dialogFormVisible" width="40%">
        <div class="updateDialogInfo">
          <el-tag>父级部门</el-tag>
          <el-input
            placeholder="请输入内容"
            v-model="parentName"
            :disabled="true"
            class="updateDialogInput el-update_input "
          ></el-input>
          <el-tag>部门名称</el-tag>
          <el-input
            v-model="updateDep.name"
            class="updateDialogInput el-update_input"
          ></el-input>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="doDepAdd">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  name: "DepMana",
  //import引入的组件需要注入到对象中才能使用",
  components: {},
  data() {
    //这里存放数据",
    return {
      //部门数据
      department: {},
      //更新部门数据
      updateDep: {},
      //父部门名
      parentName: "",
      //树组件绑定配置
      departmentProps: {
        children: "children",
        label: "name"
      },
      // 添加部门对话框
      dialogFormVisible: false,
      //过滤属性
      filterDepText: ""
    };
  },
  //监听属性 类似于data概念",
  computed: {},
  //监控data中的数据变化",
  watch: {
    //过滤数据监视
    filterDepText(val) {
      this.$refs.tree.filter(val);
    }
  },
  //方法集合",
  methods: {
    //初始化角色菜单信息
    initAllDeps() {
      this.getRequest("/system/basic/department/").then(resp => {
        if (resp) {
          this.department = resp;
        }
      });
    },
    //过滤方法
    filterDepNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    //添加部门
    showAddDep(data) {
      this.dialogFormVisible = true;
      this.updateDep.parentId = data.id;
      this.parentName = data.name;
      console.log(data);
    },
    //添加部门
    doDepAdd() {
      this.postRequest("/system/basic/department/", this.updateDep)
        .then(resp => {
          if (resp) {
            this.dialogFormVisible = false;
            this.updateDep = {};
            this.initAllDeps();
            this.addDep2Deps(this.department, resp.obj);
          }
        })
        .catch(() => {});
    },
    //更新页面部门数据，防止连续操作出错
    addDep2Deps(allDeps, obj) {
      for (let i = 0; i < allDeps.length; i++) {
        let d = allDeps[i];
        if (d.id == obj.parentId) {
          d.children = d.children.concat(obj);
          if (d.children > 0) {
            d.isParent = true;
          }
          return;
        } else {
          this.addDep2Deps(d.children, obj);
        }
      }
    },
    //删除部门
    doDepDelete(data) {
      if (data.isParent) {
        this.$message.error("下面有子部门关联，部门删除失败！");
      } else {
        this.$confirm(
          "此操作将永久删除 [" + data.name + "] 部门,是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "waring"
          }
        )
          .then(() => {
            this.deleteRequest("/system/basic/department/" + data.id).then(
              resp => {
                if (resp) {
                  this.initAllDeps();
                  this.doRemoveDepFromTree(null, this.department, data.id);
                }
              }
            );
          })
          .catch(() => {
            this.$message.info("已取消删除！");
          });
      }
    },
    //更新页面部门数据，解决删除了子部门后，仍被判断为父级部门的问题
    doRemoveDepFromTree(p, deps, id) {
      for (let i = 0; i < deps.length; i++) {
        let d = deps[i];
        if (d.id == id) {
          deps.splice(i, 1);
          if (deps.length === 0) {
            p.isParent = false;
          }
          return;
        } else {
          this.doRemoveDepFromTree(d, d.children, id);
        }
      }
    }
  },
  //生命周期 - 创建之前",数据模型未加载,方法未加载,html模板未加载
  beforeCreate() {},

  //生命周期 - 创建完成（可以访问当前this实例）",数据模型已加载，方法已加载,html模板已加载,html模板未渲染
  created() {},
  //生命周期 - 挂载之前",html模板未渲染
  beforeMount() {},

  //生命周期 - 挂载完成（可以访问DOM元素）",html模板已渲染
  mounted() {
    this.initAllDeps();
  },

  //生命周期 - 更新之前",数据模型已更新,html模板未更新
  beforeUpdate() {},
  //生命周期 - 更新之后",数据模型已更新,html模板已更新
  updated() {},
  //生命周期 - 销毁之前",
  beforeDestroy() {},
  destroyed() {},
  //生命周期 - 销毁完成",
  //如果页面有keep-alive缓存功能，这个函数会触发",
  activated() {}
};
</script>

<style>
.depTreeSearch {
  width: 500px;
}
.dep .el-tree-node__content {
  height: 48px;
}
.dep .el-tree-node {
  font-size: 20px;
}
.dep .custom-tree-node {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.dep .custom-tree-button {
  padding: 5px;
}
.dep .updateDialogInfo {
  width: 500px;
  margin: 0 auto;
}
.dep .updateDialogInput {
  width: 350px;
}
</style>
